"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { BarChart3, User, Lock, LogIn, Eye, EyeOff } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { useAuth } from "@/lib/contexts/auth-context"
import { withGuest } from "@/components/auth-guard"
import { ThemeToggle } from "@/components/theme-toggle"

function LoginPage() {
  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const router = useRouter()
  const { toast } = useToast()
  const { login, isLoggingIn, loginError, logout } = useAuth()

  // 进入登录页时，确保清除所有认证状态（防止401跳转循环）
  useEffect(() => {
    // 检查是否是从401错误跳转而来
    const isFromUnauthorized = sessionStorage.getItem('auth-redirecting')
    if (isFromUnauthorized) {
      // 强制登出，清除所有状态
      logout()
      sessionStorage.removeItem('auth-redirecting')
      console.log('🔄 从401跳转而来，已清除所有认证状态')
    }
  }, [logout])

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!username.trim() || !password.trim()) {
      toast({
        title: "登录失败",
        description: "请输入用户名和密码",
        variant: "destructive",
        duration: 3000,
      })
      return
    }

    const result = await login({ username, password })
    if (result) {
      // 登录成功，延迟跳转确保状态已保存
      // 使用 setTimeout 确保 localStorage 写入和状态更新完成
      setTimeout(() => {
        router.push('/')
      }, 100)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-background via-background to-muted/20 flex items-center justify-center p-4 relative">
      {/* 主题切换按钮 */}
      <div className="absolute top-6 right-6">
        <ThemeToggle />
      </div>

      <div className="w-full max-w-md">
        {/* Logo和标题 */}
        <div className="text-center mb-8">
          <div className="flex justify-center mb-6">
            <div className="flex items-center justify-center w-20 h-20 rounded-full bg-accent/10 border-2 border-accent/20">
              <BarChart3 className="w-10 h-10 text-accent" />
            </div>
          </div>
          <h1 className="text-3xl font-bold text-foreground bg-gradient-to-r from-foreground to-accent bg-clip-text text-transparent">
            股票AI智能分析系统
          </h1>
          <p className="text-muted-foreground mt-3 text-base">专业的股票推荐分析和监控平台</p>
        </div>

        {/* 登录卡片 */}
        <Card className="shadow-xl border-accent/20 backdrop-blur-sm bg-card/95">
          <CardHeader className="pb-6">
            <CardTitle className="text-2xl text-center font-bold">用户登录</CardTitle>
          </CardHeader>
          <CardContent className="pb-6">
            <form onSubmit={handleLogin} className="space-y-5">
              {/* 用户名输入 */}
              <div className="space-y-2">
                <label htmlFor="username" className="text-sm font-medium text-foreground">
                  用户名
                </label>
                <div className="relative group">
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground group-focus-within:text-accent transition-colors" />
                  <Input
                    id="username"
                    type="text"
                    placeholder="请输入用户名"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    className="pl-10 h-11 bg-background/50 border-muted-foreground/20 focus:border-accent focus:ring-accent/20 transition-all"
                    disabled={isLoggingIn}
                  />
                </div>
              </div>

              {/* 密码输入 */}
              <div className="space-y-2">
                <label htmlFor="password" className="text-sm font-medium text-foreground">
                  密码
                </label>
                <div className="relative group">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground group-focus-within:text-accent transition-colors" />
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="请输入密码"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="pl-10 pr-10 h-11 bg-background/50 border-muted-foreground/20 focus:border-accent focus:ring-accent/20 transition-all"
                    disabled={isLoggingIn}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-muted-foreground hover:text-accent transition-colors"
                    disabled={isLoggingIn}
                  >
                    {showPassword ? (
                      <EyeOff className="w-4 h-4" />
                    ) : (
                      <Eye className="w-4 h-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* 登录按钮 */}
              <div className="pt-2">
                <Button
                  type="submit"
                  className="w-full h-11 bg-accent hover:bg-accent/90 text-accent-foreground font-medium shadow-lg hover:shadow-xl transition-all duration-200"
                  disabled={isLoggingIn || !username.trim() || !password.trim()}
                >
                  {isLoggingIn ? (
                    <>
                      <LogIn className="w-4 h-4 mr-2 animate-spin" />
                      登录中...
                    </>
                  ) : (
                    <>
                      <LogIn className="w-4 h-4 mr-2" />
                      登录系统
                    </>
                  )}
                </Button>
              </div>
            </form>

            {/* 其他选项 */}
            <div className="mt-6 text-center">
              <p className="text-sm text-muted-foreground">
                没有账号？
                <Link
                  href="/register"
                  className="text-accent hover:text-accent/80 hover:underline ml-1 font-medium"
                >
                  立即注册
                </Link>
              </p>
            </div>
          </CardContent>
        </Card>

        {/* 页脚信息 */}
        <div className="mt-8 text-center">
          <div className="flex items-center justify-center space-x-3 text-xs text-muted-foreground/60">
            <span>© 2024</span>
            <span className="w-1 h-1 bg-muted-foreground/40 rounded-full"></span>
            <span>安全登录</span>
            <span className="w-1 h-1 bg-muted-foreground/40 rounded-full"></span>
            <span>数据加密</span>
          </div>
        </div>
      </div>
    </div>
  )
}

export default withGuest(LoginPage)